package com.example.demo.util;

import com.example.demo.exception.BusyException;
import org.apache.commons.mail.SimpleEmail;

import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

public class EmailUtil {
    public static String sendEmail(String fromEmail,String toEmail){
        SimpleEmail se =new SimpleEmail();
        se.setHostName("smtp.qq.com");
        se.setSmtpPort(465);
        se.setSSLOnConnect(true);
        se.setAuthentication(fromEmail, "ruhwgvgyvnphdgji");
        String code="";
        try {
            se.addTo(toEmail);
            se.setFrom(fromEmail);
            se.setSubject("System verify code");
            Random random=new SecureRandom();
            for(int i=0;i<6;i++) {
                code+=random.nextInt(10);
            }
            se.setMsg("Your code is："+code);
            se.send();
        } catch (Exception e) {
            return null;
        }
        return code;
    }

    public static void sendEmailAsyncWithRetry(Runnable runnable, int maxRetries, Executor executor) {
        if (runnable == null) {
            throw new BusyException("Runnable cannot be null");
        }
        if (maxRetries < 0) {
            throw new BusyException("Max retries cannot be negative");
        }
        if (executor == null) {
            throw new BusyException("Executor cannot be null");
        }
        AtomicInteger retryCount = new AtomicInteger(0);
        Runnable retryRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (Exception e) {
                    int currentRetry = retryCount.incrementAndGet();
                    if (currentRetry <= maxRetries) {
                        // 重试
                        executor.execute(this);
                    } else {
                        // 重试次数耗尽，完成异常
                        throw new BusyException("send email error by retry counts");
                    }
                }
            }
        };
        executor.execute(retryRunnable);
    }
}
